package cn.tedu.net;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {

    private Socket socket;

    public ChatClient()throws Exception{
        socket = new Socket("localhost",8080);
        // 启动服务助手，用以接收服务返回的数据
        ServerHandler serverHandler = new ServerHandler();
        serverHandler.start();

        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);
        PrintWriter pw = new PrintWriter(bw,true);

        //
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入内容：");
            String s = scanner.nextLine();
            if("exit".equals(s)){
                break;
            }
            pw.println(s);
        }
        pw.close();
    }


    // 用来接收服务端发回来的消息
    class ServerHandler extends Thread{
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br =  new BufferedReader(isr);
                String line = null;
                while((line=br.readLine())!=null){
                    System.out.println(line);
                }
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)throws Exception {
        ChatClient chatClient =  new ChatClient();
    }
}
